"""
@Author    : ghenyar
@Time      : 2025/8/27 12:40
@File      : __init__.py
@Desc      : 后台管理子应用入口
"""
from typing import Callable, Awaitable

from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import Response

from starlette.middleware.cors import CORSMiddleware
from app.admin.middleware import AdminMiddleware

from app.common.exception.handlers import (
    base_exception_handler,
    validation_exception_handler,
    sqlalchemy_exception_handler,
    general_exception_handler,
    http_exception_handler
)
from app.common.exception.exceptions import BasesException

from sqlalchemy.exc import SQLAlchemyError

from .controller.login import router as login_router
from .controller.setting import router as settings_router
from .controller.menus import router as menus_router
from .controller.role import router as role_router
from .controller.admin import router as admin_router

app_admin = FastAPI(
    title="Admin API",
    description="后台管理接口",
    version="1.0.0"
)

# 注册异常处理器
ExceptionHandler = Callable[[Request, Exception], Awaitable[Response]]

app_admin.add_exception_handler(BasesException, base_exception_handler)  # type: ignore[arg-type]
app_admin.add_exception_handler(HTTPException, http_exception_handler)  # type: ignore[arg-type]
app_admin.add_exception_handler(RequestValidationError, validation_exception_handler)  # type: ignore[arg-type]
app_admin.add_exception_handler(SQLAlchemyError, sqlalchemy_exception_handler)  # type: ignore[arg-type]
app_admin.add_exception_handler(Exception, general_exception_handler)

# 加载中间件
app_admin.add_middleware(AdminMiddleware)

# 跨域配置
app_admin.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["Content-Range", "Content-Length", "Content-Disposition", "Content-Type"],  # 显式暴露这些头部
)
# 路由
app_admin.include_router(login_router, tags=["登录/验证码"])
app_admin.include_router(settings_router, prefix="/sett", tags=["系统设置/配置"])
app_admin.include_router(menus_router, prefix="/menus", tags=["菜单管理"])
app_admin.include_router(role_router, prefix="/role", tags=["角色管理"])
app_admin.include_router(admin_router, prefix="/admins", tags=["管理员管理"])
